﻿using FRRJIf;
using RJi.FanucInterface3.Common.Internal;
using RJi.FanucInterface3.Models;

namespace RJi.FanucInterface3.DataParser.Internal;

internal class DataSysVarParser : IDataParser
{
    public bool CanHandle(VariableMetadata metadata)
    {
        return metadata.DataType == typeof(DataSysVar) || metadata.DataType == typeof(DataSysVar[]);
    }

    public object? Parse(VariableMetadata metadata)
    {
        if (metadata.DataType == typeof(DataSysVar))
        {
            object? value = null;
            if (metadata.VariableRef is DataSysVar sysVar) return sysVar.GetValue(ref value) ? new RbtSysVar(sysVar.SysVarName, value) : null;
            return null;
        }

        // 如果是数组返回以下内容
        var sysVars = (DataSysVar[])metadata.VariableRef;
        var vars = new RbtSysVar[metadata.Count];

        for (var i = 0; i < metadata.Count; i++)
        {
            object? value = null;
            if (sysVars[i].GetValue(ref value))
                vars[i] = new RbtSysVar(sysVars[i].SysVarName, value);
        }

        return vars.Length == 0 ? null : vars;
    }
}